'use client'

import { useEffect, useState } from 'react'
import { Card } from '@/components/ui/card'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Button } from '@/components/ui/button'
import { FunnelChart, Funnel, LabelList, ResponsiveContainer, Tooltip, Cell } from 'recharts'
import { Download } from 'lucide-react'
import { DatePickerWithRange } from '@/components/DatePickerWithRange'
import * as XLSX from 'xlsx'
import { addDays } from 'date-fns'
import type { DateRange as DayPickerDateRange } from 'react-day-picker'

type TimeRange = 'today' | 'week' | 'month' | 'custom'
type ViewType = 'chart' | 'table'
type MetricType = 'tangzhuang' | 'movie' | 'hanfu' | 'aivideo'

interface DateRange {
  from: Date
  to: Date
}

interface FunnelData {
  name: string
  value: number
  percent: number
  uv: number
  uvPercent: number
}

const STEPS = ['点击模块', '确认风格', '生成结果']
const METRICS = [
  { id: 'tangzhuang', label: '唐装写真' },
  { id: 'movie', label: '热门影视剧妆造' },
  { id: 'hanfu', label: '制式汉服' },
  { id: 'aivideo', label: 'AI唐风视频' },
] as const

const TIME_RANGES = [
  { value: 'today', label: '本日' },
  { value: 'week', label: '本周' },
  { value: 'month', label: '本月' },
  { value: 'custom', label: '自定义' },
]

const formatNumber = (num: number) => {
  return new Intl.NumberFormat('zh-CN').format(num)
}

const calculatePercent = (current: number, previous: number) => {
  if (previous === 0) return 0
  return Math.round((current / previous) * 100)
}

// 漏斗图颜色配置 - 从深到浅的渐变
const COLORS = {
  pv: {
    gradient: ['#003eb3', '#1677FF', '#4096ff'],  // 深蓝 -> 中蓝 -> 浅蓝
    textColor: '#fff'  // 漏斗内文字颜色
  },
  uv: {
    gradient: ['#237804', '#52C41A', '#95de64'],  // 深绿 -> 中绿 -> 浅绿
    textColor: '#fff'  // 漏斗内文字颜色
  }
}

const formatDateToString = (date: Date) => {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

export function UserBehaviorAnalysis() {
  const [timeRange, setTimeRange] = useState<TimeRange>('today')
  const [dateRange, setDateRange] = useState<DateRange>({
    from: new Date(),
    to: new Date()
  })
  const [viewType, setViewType] = useState<ViewType>('chart')
  const [selectedMetrics, setSelectedMetrics] = useState<MetricType[]>(['tangzhuang'])
  const [funnelData, setFunnelData] = useState<FunnelData[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [timeDescription, setTimeDescription] = useState<string>('')

  const toggleMetric = (metric: MetricType) => {
    setSelectedMetrics(prev => {
      if (prev.includes(metric)) {
        if (prev.length === 1) return prev
        return prev.filter(m => m !== metric)
      }
      return [...prev, metric]
    })
  }

  const fetchData = async () => {
    try {
      setLoading(true)
      setError(null)
      
      let startDate, endDate
      const now = new Date()
      const today = formatDateToString(now)  // 今天的日期，如 "2025-01-15"
      
      switch (timeRange) {
        case 'today': {
          // 今天
          startDate = today
          endDate = today
          break
        }
        case 'week': {
          // 今天往前推6天
          const start = new Date(now)
          start.setDate(now.getDate() - 6)  // 前6天
          startDate = formatDateToString(start)
          endDate = today
          break
        }
        case 'month': {
          // 本月1号到今天
          const currentYear = now.getFullYear()
          const currentMonth = now.getMonth() + 1  // getMonth() 返回 0-11
          const firstDay = `${currentYear}-${currentMonth.toString().padStart(2, '0')}-01`
          startDate = firstDay
          endDate = today
          break
        }
        case 'custom': {
          if (!(dateRange.from instanceof Date) || !(dateRange.to instanceof Date)) {
            throw new Error('无效的日期范围')
          }
          if (dateRange.from > dateRange.to) {
            throw new Error('开始日期不能晚于结束日期')
          }
          
          startDate = formatDateToString(dateRange.from)
          endDate = formatDateToString(dateRange.to)
          break
        }
      }

      console.log('Fetching data with:', { 
        timeRange,
        startDate,
        endDate,
        today,
        startDateTime: new Date(startDate + 'T00:00:00').toLocaleString(),
        endDateTime: new Date(endDate + 'T00:00:00').toLocaleString()
      })

      const promises = selectedMetrics.map(metric => 
        fetch(
          `/api/user-behavior/funnel?startDate=${startDate}&endDate=${endDate}&metrics[]=${metric}`,
          {
            headers: {
              'Accept': 'application/json',
            }
          }
        ).then(async res => {
          if (!res.ok) {
            const errorText = await res.text()
            console.error('API Error Response:', errorText)
            throw new Error(`API请求失败: ${errorText}`)
          }
          const data = await res.json()
          console.log(`API Response for ${metric}:`, data)
          return data
        })
      )
      
      const results = await Promise.all(promises)

      // Transform API data to funnel chart format
      const newFunnelData: FunnelData[] = STEPS.map((step, stepIndex) => {
        const stepData = {
          name: step,
          value: 0,
          uv: 0,
          percent: 0,
          uvPercent: 0
        }

        selectedMetrics.forEach((metric, metricIndex) => {
          const metricData = results[metricIndex]?.[metric]
          if (metricData?.pv && metricData?.uv) {
            stepData.value += metricData.pv[stepIndex] || 0
            stepData.uv += metricData.uv[stepIndex] || 0
          }
        })

        return stepData
      })

      // 计算转化率
      newFunnelData.forEach((data, index) => {
        if (index === 0) {
          data.percent = 100
          data.uvPercent = 100
        } else {
          const prevValue = newFunnelData[index - 1].value
          const prevUV = newFunnelData[index - 1].uv
          data.percent = calculatePercent(data.value, prevValue)
          data.uvPercent = calculatePercent(data.uv, prevUV)
        }
      })

      console.log('Transformed funnel data:', newFunnelData)
      setFunnelData(newFunnelData)
    } catch (error) {
      console.error('Error fetching funnel data:', error)
      setError(error instanceof Error ? error.message : '获取数据失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchData()
  }, [timeRange, selectedMetrics, dateRange])

  const handleDownloadTable = () => {
    const data = funnelData.map(item => ({
      '步骤': item.name,
      '风格': selectedMetrics.map(m => 
        METRICS.find(metric => metric.id === m)?.label
      ).join(', '),
      'PV': item.value,
      'PV转化率': `${item.percent}%`,
      'UV': item.uv,
      'UV转化率': `${item.uvPercent}%`
    }))

    const ws = XLSX.utils.json_to_sheet(data)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '漏斗转化分析')
    
    const metrics = selectedMetrics.map(m => 
      METRICS.find(metric => metric.id === m)?.label
    ).join('-')
    const fileName = `漏斗转化分析_${metrics}_${timeRange}_${new Date().toISOString().split('T')[0]}.xlsx`
    
    XLSX.writeFile(wb, fileName)
  }

  const CustomTooltip = ({ active, payload, type }: any) => {
    if (active && payload && payload.length) {
      const data = payload[0].payload
      const isUV = type === 'uv'
      return (
        <div className="bg-white p-3 shadow-lg rounded-lg border">
          <p className="font-medium">{data.name}</p>
          <p className="text-sm">
            {isUV ? '独立访客(UV)' : '访问量(PV)'}: {formatNumber(isUV ? data.uv : data.value)}
          </p>
          {data.percent !== undefined && data.percent !== 100 && (
            <p className="text-sm">转化率: {data.percent}%</p>
          )}
        </div>
      )
    }
    return null
  }

  const renderFunnel = (type: 'pv' | 'uv') => {
    const isUV = type === 'uv'
    const colors = COLORS[type]
    const data = funnelData.map(item => ({
      name: item.name,
      value: isUV ? item.uv : item.value,
      percent: isUV ? item.uvPercent : item.percent,
      uv: item.uv,
      uvPercent: item.uvPercent
    }))

    return (
      <div className="relative w-1/2 px-4">
        <h4 className="text-center mb-4 text-sm font-medium text-gray-500">
          {isUV ? '独立访客(UV)漏斗' : '访问量(PV)漏斗'}
        </h4>
        <ResponsiveContainer width="100%" height={400}>
          <FunnelChart>
            <Tooltip content={(props) => <CustomTooltip {...props} type={type} />} />
            <Funnel
              dataKey="value"
              data={data}
              isAnimationActive
              stroke="#fff"
              strokeWidth={2}
            >
              {data.map((entry, index) => (
                <LabelList
                  key={`label-${index}`}
                  position="center"
                  fill={colors.textColor}
                  stroke="none"
                  content={({ x, y, width, height, value, name, percent }: any) => (
                    <g>
                      <text 
                        x={x + width/2} 
                        y={y + height/2} 
                        fill={colors.textColor} 
                        textAnchor="middle"
                        className="text-sm"
                      >
                        <tspan x={x + width/2} dy="-12" className="font-medium">{name}</tspan>
                        <tspan x={x + width/2} dy="20">
                          {formatNumber(value)}
                        </tspan>
                        {percent !== undefined && percent !== 100 && (
                          <tspan x={x + width/2} dy="20">
                            转化率: {percent}%
                          </tspan>
                        )}
                      </text>
                    </g>
                  )}
                />
              ))}
              {colors.gradient.map((color, index) => (
                <Cell key={`cell-${index}`} fill={color} />
              ))}
            </Funnel>
          </FunnelChart>
        </ResponsiveContainer>
      </div>
    )
  }

  const renderChart = () => (
    <div className="flex pt-4">
      {renderFunnel('pv')}
      {renderFunnel('uv')}
    </div>
  )

  const renderTable = () => (
    <div className="mt-4 space-y-4">
      <div className="flex justify-end">
        <Button
          variant="outline"
          size="sm"
          onClick={handleDownloadTable}
          className="flex items-center gap-2"
        >
          <Download className="w-4 h-4" />
          下载表格
        </Button>
      </div>
      <div className="border rounded-lg">
        <table className="w-full">
          <thead>
            <tr className="border-b bg-gray-50">
              <th className="text-left p-4">步骤</th>
              <th className="text-left p-4">风格</th>
              <th className="text-right p-4">PV</th>
              <th className="text-right p-4">PV转化率</th>
              <th className="text-right p-4">UV</th>
              <th className="text-right p-4">UV转化率</th>
            </tr>
          </thead>
          <tbody>
            {funnelData.map((data, index) => (
              <tr key={data.name} className="border-b last:border-0">
                <td className="p-4">{data.name}</td>
                <td className="p-4">
                  {selectedMetrics.map(m => 
                    METRICS.find(metric => metric.id === m)?.label
                  ).join(', ')}
                </td>
                <td className="text-right p-4">{formatNumber(data.value)}</td>
                <td className="text-right p-4">{data.percent}%</td>
                <td className="text-right p-4">{formatNumber(data.uv || 0)}</td>
                <td className="text-right p-4">{data.uvPercent}%</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )

  // 更新时间描述
  const updateTimeDescription = (newTimeRange: TimeRange, customRange?: DateRange) => {
    const today = new Date()
    let description = ''

    switch (newTimeRange) {
      case 'today':
        description = `${today.getFullYear()}年${today.getMonth() + 1}月${today.getDate()}日`
        break
      case 'week':
        const weekStart = new Date(today)
        weekStart.setDate(today.getDate() - 6)
        description = `${weekStart.getMonth() + 1}月${weekStart.getDate()}日 至 ${today.getMonth() + 1}月${today.getDate()}日`
        break
      case 'month':
        description = `${today.getFullYear()}年${today.getMonth() + 1}月1日 至 ${today.getMonth() + 1}月${today.getDate()}日`
        break
      case 'custom':
        if (customRange?.from && customRange?.to) {
          const fromDate = customRange.from.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
          const toDate = customRange.to.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
          description = `${fromDate} 至 ${toDate}`
        }
        break
    }

    setTimeDescription(description)
  }

  // 初始化时设置时间描述
  useEffect(() => {
    updateTimeDescription('today')
  }, [])

  const handleTimeRangeChange = (newTimeRange: string) => {
    setTimeRange(newTimeRange as TimeRange)
    updateTimeDescription(newTimeRange as TimeRange, dateRange)
  }

  const handleDateRangeChange = (range: DayPickerDateRange | undefined) => {
    if (range?.from && range?.to) {
      const newDateRange: DateRange = {
        from: range.from,
        to: range.to
      }
      setDateRange(newDateRange)
      updateTimeDescription('custom', newDateRange)
    }
  }

  return (
    <Card className="p-6">
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-medium">转化漏斗分析</h3>
          <Tabs
            value={viewType}
            onValueChange={(value) => setViewType(value as ViewType)}
          >
            <TabsList>
              <TabsTrigger value="chart">图表</TabsTrigger>
              <TabsTrigger value="table">表格</TabsTrigger>
            </TabsList>
          </Tabs>
        </div>

        <Card className="p-6 shadow-lg">
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
                {METRICS.map(option => (
                <Button
                  key={option.id}
                  variant={selectedMetrics.includes(option.id as MetricType) ? "default" : "outline"}
                  onClick={() => toggleMetric(option.id as MetricType)}
                    className="shadow-sm hover:shadow-md transition-all duration-200"
                >
                  {option.label}
                </Button>
              ))}
            </div>

            <div className="flex items-center gap-4">
                <div className="flex items-center gap-2">
                  {TIME_RANGES.map(range => (
                    <Button
                      key={range.value}
                      variant={timeRange === range.value ? "default" : "outline"}
                      onClick={() => handleTimeRangeChange(range.value)}
                      className="shadow-sm hover:shadow-md transition-all duration-200"
                    >
                      {range.label}
                    </Button>
                  ))}
                </div>
                {timeRange === 'custom' && (
                  <div className="relative">
                    <DatePickerWithRange
                      value={{
                        from: dateRange.from,
                        to: dateRange.to
                      }}
                      onChange={handleDateRangeChange}
                    />
                  </div>
                )}
              </div>
            </div>
            {/* 时间范围显示 */}
            <div className="flex items-center pt-4 border-t border-gray-100">
              <div className="text-sm text-gray-500">
                当前数据范围：
                <span className="ml-2 text-gray-900 font-medium">{timeDescription}</span>
              </div>
            </div>
          </div>
        </Card>

        {error ? (
          <div className="h-[300px] flex items-center justify-center text-red-500">
            {error}
          </div>
        ) : loading ? (
          <div className="h-[300px] flex items-center justify-center">
            加载中...
        </div>
        ) : viewType === 'chart' ? (
          renderChart()
        ) : (
          renderTable()
        )}
      </div>
    </Card>
  )
} 